<template>
  <div>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      status-icon
      hide-required-asterisk="false"
    >
      <el-form-item label="选择封面图片" height="40">
        <el-upload
          action="#"
          :multiple="false"
          accept=".jpg,.jpeg,.png"
          :show-file-list="true"
          list-type="picture-card"
          @change="handelFileChange"
          :auto-upload="false"
        >
          <el-image class="avatar" v-if="imageUrl" :src="imageUrl" />
          <el-icon v-else>
            <Plus />
          </el-icon>
          <template #tip>
            <div class="el-upload__tip">图片大小不能超过 500kb</div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="选择文件" height="40">
        <el-upload
          action="#"
          :multiple="false"
          accept=".xls,.xlsx,.csv,.xlsm,.xlsb"
          :file-list="fileList"
          :show-file-list="true"
          @change="handelFileExcle"
          :auto-upload="false"
        >
          <el-button type="primary">点击上传</el-button>
        </el-upload>
        <div v-for="(file, index) in fileList" :key="index" style="margin-left: 20px; color:#606266">
          {{ file.name }}
        </div>
      </el-form-item>
      <el-form-item label="请按照模版格式上传" height="40" label-width="160">
        <el-button type="primary" @click="handleFileImport"
          ><el-icon style="margin-right: 5px"> <Download /> </el-icon
          >下载导入食物文件模版</el-button
        >
      </el-form-item>
    </el-form>

    <span class="dialog-footer">
      <el-button type="primary" @click="submitForm(ruleFormRef)"
        >提交</el-button
      >
      <el-button @click="resetForm(ruleFormRef)">重置表单</el-button>
      <el-button @click="handleReturn">取消</el-button>
    </span>
  </div>
</template>

<script>
import { ref } from 'vue'
import request from '../../utils/request'
import { ElNotification } from 'element-plus'
import { useRouter } from 'vue-router'
export default {
  components: {},
  setup() {
    const router = useRouter()
    const selectedFile = ref(null)
    const selectExcel = ref(null)
    // 重置表单
    const resetForm = (formEl) => {
      imageUrl.value = ''
      formEl.resetFields()
    }

    // 获取文件数据
    const imageUrl = ref('')
    const handelFileChange = (file) => {
      const isLt500k = file.raw.size / 1024 < 500
      if (!isLt500k) {
        ElNotification({
          title: '图片过大',
          message: '图片不能超过500k',
        })
        return
      }
      selectedFile.value = file.raw

      imageUrl.value = URL.createObjectURL(file.raw)
    }
    const fileList = ref([])
    const handelFileExcle = (file) => {
      fileList.value.push(file)
      if (fileList.value.length>1) {
        fileList.value.splice(0,1)
      }
      selectExcel.value = file.raw
    }
    // 处理添加方法的参数数据
    const processFormData = () => {
      const formData = new FormData()
      if (selectedFile.value) {
        const fileName = selectedFile.value.name
        formData.append('avator', selectedFile.value, fileName)
      }
      if (selectExcel.value) {
        const excelName = selectExcel.value.name
        formData.append('excelfile', selectExcel.value, excelName)
      }
      return formData
    }

    const formData = ref(null)
    // 提交表单
    const submitForm = async () => {
      if (!selectedFile.value) {
        ElNotification({
          title: '添加失败',
          message: '请添加封面图',
        })
        return
      }
      if (!selectExcel.value) {
        ElNotification({
          title: '添加失败',
          message: '请上传文件',
        })
        return
      }
      formData.value = processFormData()
      await request
        .request({
          url: '/food/excelImportFoods',
          method: 'post',
          data: formData.value,
        })
        .then((res) => {
          if (res.data.code == 200) {
            ElNotification({
              title: '导入成功',
              message: '成功导入食物信息',
            })
            router.push('/foodTable')
          } else {
            ElNotification({
              title: '导入失败',
              message: '请联系管理员检查失败原因',
            })
          }
        })
        .catch((e) => {
          console.log(e)
          ElNotification({
            title: '导入失败',
            message: '请联系管理员检查失败原因',
          })
        })
    }

    const handleReturn = () => {
      router.push('/foodTable')
    }

    const handleFileImport = () => {
      var a = document.createElement('a') //创建一个<a></a>标签
      a.href = '/static/text.xlsx' // 给a标签的href属性值加上地址，注意，这里是绝对路径，不用加 点.
      a.download = '食物模版.xlsx' //设置下载文件文件名，这里加上.xlsx指定文件类型，pdf文件就指定.fpd即可
      a.style.display = 'none' // 障眼法藏起来a标签
      document.body.appendChild(a) // 将a标签追加到文档对象中
      a.click() // 模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
      a.remove() // 一次性的，用完就删除a标签
    }
    return {
      fileList,
      imageUrl,
      handelFileChange,
      submitForm,
      resetForm,
      handleReturn,
      handleFileImport,
      handelFileExcle,
    }
  },
}
</script>

<style lang="scss" scoped></style>

<style>
.el-upload--text {
  height: auto;
  width: auto;
}

.mavonEditor {
  width: 100%;
  height: 100%;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.el-upload-list__item.is-ready,
.el-upload-list__item.is-uploading {
  display: none !important;
}
</style>
